import httpConfig from "../config/http.config.js";
import md5 from "js-md5";
import Auth from "../utils/auth.js";
import Helper from "../utils/helper.js";

// import { Base64 } from "js-base64";

const http = {};

http.post = (url, param, loading = true, requireToken = true, encrypt = 0) => {
	return request(url, param, loading, requireToken, 'POST', encrypt)
};
http.get = (url, param, loading, requireToken = true, encrypt = 3) => {
	return request(url, param, loading, requireToken, 'GET', encrypt)
}

let queryTime = {},
	interval = 300;
let Base64 = require('js-base64/base64.js').Base64;

const request = (url, param, loading, requireToken = true, method = 'POST', encrypt_type = 3) => {
	// 处理防抖节流
	if (!param) param = {};
	let now = +new Date();
	let key = md5(method + url);
	let last = queryTime[key] || 0;
	// if (now - last >= interval) {
	queryTime[key] = now;
	if (loading) {
		uni.showLoading({
			title: '加载中...'
		});
	}

	return new Promise((resolve, reject) => {
		let token = Auth.getToken();
		let store_id = uni.getStorageSync('store_id') || 0;
		if (token.length <= 0 && requireToken) {
			reject(url + '未登录或已过期');
			uni.hideLoading();
			return;
		}
		now = parseInt(now / 1000);
		let key = 'xianjiazheng.com';
		let paramStr = JSON.stringify(param),
			sign = md5(key + now + paramStr),
			data = {
				encrypt: Base64.encode(paramStr)
			};

		uni.request({
			url: httpConfig.baseUrl + url,
			method,
			data: (encrypt_type == 1 || encrypt_type == 3) ? data : param,
			header: {
				Authorization: `Bearer ${token}`,
				"Encrypt-Type": encrypt_type,
				"Store-Id": store_id,
				timestamp: now,
				sign
			},
			success: (res) => {
				if (res.data.code == 1) {
					let encrypt = res.data.data.encrypt || '';
					if (encrypt.length > 0) {
						let data = Base64.decode(encrypt);
						data = data.replace(key, '');
						data = Base64.decode(data.split('').reverse().join(''));
						res.data.data = JSON.parse(data);
					}
				} else if (res.data.code <= -1) {
					uni.removeStorageSync('token');
					uni.removeStorageSync('userInfo');
					uni.removeStorageSync('refresh_token');
					console.log(getCurrentPages(), 8888888888);
					let pages = getCurrentPages();
					let jumpPage = pages[pages.length - 1].$page.fullPath;
					uni.setStorageSync('jumpPage', jumpPage)
					uni.redirectTo({
						url: '/pages/login/login'
					})
					reject('登录过期');
					return;
				} else if (res.data.code == 0) {
					// Helper.toast(res.data.msg);
				}
				// console.log(res.data, url, '返回数据');
				resolve(res.data);
			},
			fail: _ => {
				uni.navigateTo({
					url: "/pages/noNetwork/noNetwork"
				})
				reject('网络繁忙!');
			},
			complete: _ => {
				if (loading) {
					uni.hideLoading();
				}
			}
		});

	});
	// } else {
	// 	return new Promise((resolve, reject) => {
	// 		reject('请求过于频繁' + url);
	// 	});
	// }
}

export default http;